
var IDBM = (function() {
    var _dbName = 'guangdongWaterMesh'
    var _dbInstance = ''
    function getDB() {
        return new Promise((resolve, reject) => {
            const req = indexedDB.open(_dbName, 1)
            req.onupgradeneeded = (evt) => {
                _dbInstance = evt.target.result
                //
                _dbInstance.createObjectStore('planIndexTimes', {
                    keyPath: 'planID'
                })
                // 流域点
                _dbInstance.createObjectStore('pointStore', {
                    keyPath: 'basin'
                })
                // 流域网格
                _dbInstance.createObjectStore('meshStore', {
                    keyPath: 'basin'
                })
                // 用来存方案
                for (var i = 0; i < 10; i++) {
                    _dbInstance.createObjectStore('planStore_' + i, {
                        keyPath: 'time'
                    })
                }
            }
            req.onsuccess = (evt) => {
                _dbInstance = evt.target.result
                if (_dbInstance.objectStoreNames.contains('planIndexTimes')) {
                    resolve(_dbInstance)
                } else {
                    console.log('没有找到planIndexTimes')
                    var DBDeleteReq = indexedDB.deleteDatabase(_dbName)
                    DBDeleteReq.onsuccess = function(event) {
                        console.log('Database deleted successfully')
                        getDB()
                    }
                }
            }
            req.onerror = () => {
                console.log(`打开数据库失败`)
                resolve(undefined)
            }
        })
    }
    getDB()
    function readPoint(basin) {
        return new Promise((resolve, reject) => {
            getDB().then(_dbInstance => {
                var req = _dbInstance.transaction(['pointStore'], 'readwrite').objectStore('pointStore').get(basin)
                req.onsuccess = () => {
                    resolve(req.result)
                }
            })
        })
    }
    function writePoint(row) {
        getDB().then(_dbInstance => {
            _dbInstance.transaction(['pointStore'], 'readwrite').objectStore('pointStore').put(row)
        })
    }
    function readMeshOut(basin) {
        return new Promise((resolve, reject) => {
            getDB().then(_dbInstance => {
                var req = _dbInstance.transaction(['meshStore'], 'readwrite').objectStore('meshStore').get(basin)
                req.onsuccess = () => {
                    resolve(req.result)
                }
            })
        })
    }
    function writeMesh(row) {
        getDB().then(_dbInstance => {
            _dbInstance.transaction(['meshStore'], 'readwrite').objectStore('meshStore').put(row)
        })
    }

    // 获取方案一条时间
    function readPlanOneTime(planID, time) {
        return new Promise((resolve, reject) => {
            _getPlanInfo(planID).then(res => {
                if (res && res.index) {
                    var storeName = 'planStore_' + res.index
                    var req = _dbInstance.transaction([storeName], 'readwrite').objectStore(storeName).get(time)
                    req.onsuccess = () => {
                        resolve(req.result)
                    }
                    req.onerror = () => {
                        console.log(`没有找到时间为${time}的数据`)
                        resolve(undefined)
                    }
                } else {
                    console.log('没有此方案信息')
                    resolve(undefined)
                }
            })
        })
    }
    // 获取方案时间列表
    function readPlanTimes(planID) {
        return new Promise((resolve, reject) => {
            _getPlanInfo(planID).then(res => {
                if (res && res.timeList && res.timeList.length > 0) {
                    resolve(res.timeList)
                } else {
                    resolve([])
                }
            })
        })
    }
    // 存方案时间表
    function writePlanTimes(planID, timeList = []) {
        _getPlanInfo(planID).then(res => {
            if (res && res.index !== undefined) {
                _setPlanInfo(planID, res.index, timeList)
            } else {
                setTimeout(() => {
                    writePlanTimes(planID, timeList)
                }, 100)
            }
        })
    }
    // 保存方案对应的store index  及时间列表
    function _setPlanInfo(planID, index, timeList = []) {
        getDB().then(_dbInstance => {
            _dbInstance.transaction(['planIndexTimes'], 'readwrite').objectStore('planIndexTimes').put({
                planID,
                index,
                timeList
            })
        })
    }
    // 获取方案对应的store Index
    function _getPlanInfo(planID) {
        return new Promise((resolve, reject) => {
            if (_dbInstance) {
                var req = _dbInstance
                    .transaction(['planIndexTimes'], 'readwrite')
                    .objectStore('planIndexTimes')
                    .get(planID)

                req.onsuccess = () => {
                    resolve(req.result)
                }
                req.onerror = () => {
                    console.log(`没有找到方案ID为${planID}的StoreIndex`)
                    resolve(undefined)
                }
            } else {
                getDB().then(_dbInstance => {
                    var req = _dbInstance
                        .transaction(['planIndexTimes'], 'readwrite')
                        .objectStore('planIndexTimes')
                        .get(planID)

                    req.onsuccess = () => {
                        resolve(req.result)
                    }
                    req.onerror = () => {
                        console.log(`没有找到方案ID为${planID}的StoreIndex`)
                        resolve(undefined)
                    }
                })
            }
        })
    }

    // 清空store
    function _clearPlanStore(index) {
        var storeName = 'planStore_' + index
        _dbInstance.transaction([storeName], 'readwrite').objectStore(storeName).clear()
    }
    function writePlan(planID, row) {
        _getPlanInfo(planID).then(res => {
            console.log(res)
            if (res) { // 找到方案对应的store
                var storeName = 'planStore_' + res.index
                _dbInstance.transaction([storeName], 'readwrite').objectStore(storeName).put(row)
            } else { // 滑找到方案对应的store
                _getPlanInfo('lastPlan').then(last => {
                    if (last) { // 找到最后一个，并+1新开store
                        var currIndex = Number(last.index)
                        currIndex++
                        currIndex = currIndex > 9 ? 0 : currIndex
                        _setPlanInfo(planID, currIndex)
                        _setPlanInfo('lastPlan', currIndex)
                        _clearPlanStore(currIndex)
                        writePlan(planID, row)
                    } else { // 没有找到最后一个，还没有初始化 进行初始化
                        _setPlanInfo('lastPlan', -1)
                        writePlan(planID, row)
                    }
                })
            }
        })
    }

    return {
        writePoint,
        readPoint,
        readMeshOut,
        writeMesh,
        readPlanTimes,
        writePlan,
        writePlanTimes,
        readPlanOneTime
    }
}())
